package com.laan.plat;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.util.FloatMath;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;

public class LaanGameSV extends SurfaceView {
	
	private SurfaceHolder holder;
	private LaanGameThread lgt;
	private float xtouch;
	
	//classes auxiliars
	private Nuvols nuvols;
//	private Peces peces;
	private Plats plats;
//	private Base base;
	public Prota prota;
	//control thread
	private boolean surfacecreated;
	private boolean threadrunning;
	//fons
	Paint fons;
	//game init
	public float startx;
	public float starty;
	
	//moviment
	private boolean zoom = false;
	private float oldDist;
	private float[] lastx;
	private float[] lasty;
//	public boolean canJump;
//	public boolean hasDowned = false;
//	public boolean hasMoved = false;
//	public float xmoved = 0f;
//	public float distmoved = 0f;
//	public static float MAXDOWNMOVE = 5f;
//	public static float MAXPTDOWNMOVE = 25f;
//	public boolean hasDowned = false;
//	public boolean hasPtDowned = false;
	
//	public Bitmap bmpJumpBtn;
//	public float xjumpbtn;
//	public float yjumpbtn;
	
	public UIButton btnJump;
	public UIButton btnLeft;
	public UIButton btnRight;
	public UIButton btnAir;
	public UIButton btnNormal;
	
	public LaanGameSV(Context context) {
		super(context);
		init();
	}

	public LaanGameSV(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	public LaanGameSV(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init();
	}
	
	private void init() {
		surfacecreated = false;
		threadrunning = false;
		holder = getHolder();
		holder.addCallback( new Callback() {
			
			@Override
			public void surfaceDestroyed(SurfaceHolder holder) {
				stopthread();
				surfacecreated = false;
			}
			
			@Override
			public void surfaceCreated(SurfaceHolder holder) {
				holder.setFormat(PixelFormat.RGBA_8888);
				
				fons = new Paint(); 
			    Shader shader = new LinearGradient(0,0,GV.Screen.metrics.widthPixels,GV.Screen.metrics.heightPixels,new int[]{0xFFC4F8FF,0xFF3071F2},null,Shader.TileMode.CLAMP);
			    fons.setShader(shader);  
			    
//			    startx = GV.Screen.metrics.widthPixels/3;
//			    starty = GV.Screen.metrics.heightPixels*2/3;
				
				nuvols = new Nuvols(getResources());
//				peces = new Peces(getResources());
				
				plats = new Plats(getResources());
				
				//IMPORTANT: plats calcula startx i starty
				
				prota = new Prota(getResources(), startx, starty);
				prota.enableGravity();
//				base = new Base();
				lastx = new float[2];
				lasty = new float[2];
				GV.Game.offsetX = 0;
				
				createButtons();
				
				surfacecreated = true;
			}
			
			@Override
			public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
				startthread();
			}
		});  
	}
	
	public void createButtons() {
		int x, y, w, h;
		w = GV.Screen.metrics.widthPixels/7;
		h = w;
		
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inPreferredConfig = Bitmap.Config.ARGB_8888;
		
		Bitmap bmpBtn = BitmapFactory.decodeResource(getResources(), R.drawable.red_button, options);
		x = GV.Screen.metrics.widthPixels - w;
		y = GV.Screen.metrics.heightPixels - h;
		btnJump = new UIButton(bmpBtn, x, y, w, h);
		
		bmpBtn = BitmapFactory.decodeResource(getResources(), R.drawable.btntornado, options);
		x -= 2*w;
		btnAir = new UIButton(bmpBtn, x, y+w/3, w*2/3, h*2/3);
		
		bmpBtn = BitmapFactory.decodeResource(getResources(), R.drawable.btnnormal, options);
		x -= w;
		btnNormal = new UIButton(bmpBtn, x, y+w/3, w*2/3, h*2/3);
		
		bmpBtn = BitmapFactory.decodeResource(getResources(), R.drawable.arrowleft, options);
		x = 0;
		btnLeft = new UIButton(bmpBtn, x, y, w, h);
		
		bmpBtn = BitmapFactory.decodeResource(getResources(), R.drawable.arrowright, options);
		x += w;
		btnRight = new UIButton(bmpBtn, x, y, w, h);
	}
	
	@Override
	protected void onDraw(Canvas canvas) { 
//		Log.i("sv", "draw");
		canvas.drawRect(0,0,getWidth(),getHeight(), fons);
//		nuvols.actualitza();
//		peces.actualitza();
		plats.actualitza();
		prota.actualitza();
//		base.actualitzaPos(xtouch);
		
		plats.colisions(); 
		
//		nuvols.draw(canvas);
		
		plats.draw(canvas);
		prota.draw(canvas);
		
		if(prota.rec.top > GV.Screen.metrics.heightPixels) {
			Intent intent = GV.Instancies.laangame.getIntent();
			GV.Instancies.laangame.finish();
			GV.Instancies.laangame.startActivity(intent);
		}
		
		drawButtons(canvas);
//		base.draw(canvas);
//		peces.draw(canvas);
		
//		peces.colisions(base.x, base.y, base.width, base.height);
		
	}
	
	public void drawButtons(Canvas canvas) {
		btnJump.draw(canvas);
		btnLeft.draw(canvas);
		btnRight.draw(canvas);
		btnAir.draw(canvas);
		btnNormal.draw(canvas);
	}
	
	public void startthread() {
		if(!surfacecreated) return;
		if(threadrunning) return;
		lgt = new LaanGameThread(this);
		lgt.setRunning(true);
		lgt.start();
		threadrunning = true;
	}
	
	public void stopthread() {
		if(!surfacecreated) return;
		if(!threadrunning) return;
		boolean retry = true;
		while (retry) {
			try {
				lgt.setRunning(false);
				lgt.join();
				threadrunning = false;
				retry = false;
				
			} catch (InterruptedException e) {}
		}
	}
	
//	@Override
//	public boolean onTouchEvent(MotionEvent e) {
//		GV.Game.prota.jump();
//		return true;
//	}
		
//		Log.i("Arrows", String.valueOf(e.getActionMasked()));
		
//		if(e.getActionMasked() == MotionEvent.ACTION_POINTER_DOWN) {
//			return GV.Instancies.laangamesv.dispatchTouchEvent(e);
//		}
		
//		boolean moveRight = false;
//		Rect btn_bounds = new Rect();
//		GV.Instancies.laangame.findViewById(R.id.game_left).getHitRect(btn_bounds);
//		boolean moveLeft = btn_bounds.contains((int)e.getX(), (int)e.getY()) && e.getActionMasked() != MotionEvent.ACTION_UP;
////		boolean move = e.getActionMasked() == MotionEvent.ACTION_DOWN || e.getActionMasked() == MotionEvent.ACTION_MOVE;
//		if(moveLeft) {
//			GV.Game.prota.moveLeft(moveLeft);
////			((ImageButton) getWindow().findViewById(R.id.game_left)).performClick();
//		}
//		else {
//			GV.Instancies.laangame.findViewById(R.id.game_right).getHitRect(btn_bounds);
//			moveRight = btn_bounds.contains((int)e.getX(), (int)e.getY()) && e.getActionMasked() != MotionEvent.ACTION_UP;
//			if(moveRight) GV.Game.prota.moveRight(moveRight);
//			else GV.Game.prota.jump();
//		}
//		return true;
//	}
	
	public void hitButtons(float x, float y, boolean move) {
		if(!move && btnJump.rec.contains(x, y)) prota.jump();
		else if(!move && btnAir.rec.contains(x, y)) prota.air();
		else if(!move && btnNormal.rec.contains(x, y)) prota.normal();
		else if(btnLeft.rec.contains(x, y)) prota.moveLeft();
		else if(btnRight.rec.contains(x, y)) prota.moveRight();
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
//		Log.i("touch", String.valueOf(event.getX()));
//		if(event.getX() > base.x) xtouch = 10;
//		else xtouch = -10;
		int actInd = event.getActionIndex();
//		Log.i("touchin", String.valueOf(event.getActionMasked()));

		if(event.getActionMasked() == MotionEvent.ACTION_DOWN) {
//			Log.i("action_down", String.valueOf(event.getPointerId(actInd)));
//			hasDowned = true;
//			xmoved = 0;
//			hasDowned = true;
			hitButtons(event.getX(actInd), event.getY(actInd), false);
			
//			Log.i("action_down", String.valueOf(event.getActionIndex()));
//			Log.i("action_down", String.valueOf(event.getX()));
//			Log.i("action_down", String.valueOf(event.getPointerId(actInd)));
			
//			GV.Game.prota.jump();
//			lastx[actInd] = event.getX(actInd);
//			lasty[actInd] = event.getY(actInd);
//			return false;
		}
		if(event.getActionMasked() == MotionEvent.ACTION_POINTER_DOWN) {
//			Log.i("action_pointer_down", String.valueOf(event.getPointerId(actInd)));
//			hasDowned = true;
//			xmoved = 0;
//			hasPtDowned = true;
//			hasDowned = false;
			hitButtons(event.getX(actInd), event.getY(actInd), false);
			
			oldDist = spacing(event);
			if(oldDist > 10f) {
				zoom = true;
			}
//			GV.Game.prota.jump();
//			Log.i("action_pointer_down", String.valueOf(event.getPointerId(actInd)));
//			
//			pointerId[actInd] = event.getPointerId(actInd);
			lastx[actInd] = event.getX(actInd);
			lasty[actInd] = event.getY(actInd);
//			return false;
			
		}
		if(event.getActionMasked() == MotionEvent.ACTION_UP) {
//			if(!hasMoved) {
//				GV.Game.prota.jump();
//			}
//			else hasMoved = false;
//			hasDowned = false;
//			Log.i("action_up", String.valueOf(event.getPointerId(actInd)));
		}
		if(event.getActionMasked() == MotionEvent.ACTION_POINTER_UP) {
//			Log.i("action_pointer_up", String.valueOf(event.getPointerId(actInd)));
//			if(!hasMoved) {
//				GV.Game.prota.jump();
//			}
//			else hasMoved = false;
//			hasPtDowned = false;
			
//			lastx[actInd] = event.getX();
			zoom = false;
//			base.saveWidth();
//			prota.saveWidth();
		}
		if(event.getActionMasked() == MotionEvent.ACTION_MOVE) {
//			Log.i("action_move", String.valueOf(event.getPointerId(actInd)));
			hitButtons(event.getX(actInd), event.getY(actInd), true);
			
//			xmoved += event.getX(actInd) - lastx[actInd];
//			if(Math.abs(xmoved) > MAXMOVE) hasMoved = true;
			
//			float distmoved = dist(event.getX(actInd), event.getY(actInd), lastx[actInd], lasty[actInd]);
//			if((hasDowned && distmoved > MAXDOWNMOVE) || (hasPtDowned && distmoved > MAXPTDOWNMOVE)) hasMoved = true;
//			Log.i("distmoved", String.valueOf(distmoved));
			
//			if(pointerId[actInd] == event.getPointerId(actInd)) {
			if(zoom) {
//				Log.i("action_zoom", String.valueOf(event.getPointerId(actInd)));
				float newDist = spacing(event);
				if(newDist > 10f) {
//					Log.i("action_dist", String.valueOf(event.getPointerId(actInd)));
					float scale = newDist/oldDist;
//					base.setWidth(scale);
					prota.setWidth(scale);
//					lastx[actInd] = event.getX(actInd);
				}
			}
			else {
//				xtouch = 2f * (event.getX(actInd) - lastx[actInd]);
//				base.actualitzaPos(xtouch);
//				lastx[actInd] = event.getX(actInd);
//				GV.Game.prota.jump();
				
			}
//			return false;
//			if(pointerId[0] == event.getPointerId(actInd)) {
//				
//			}
//			xtouch = 2f * (event.getX() - lastx);
//			base.actualitzaPos(xtouch);
//			lastx = event.getX();
		}
		return true;
	}
	
	private float spacing(MotionEvent event) {
	   float x = event.getX(0) - event.getX(1);
	   float y = event.getY(0) - event.getY(1);
	   return FloatMath.sqrt(x * x + y * y);
	}
	
	private float dist(float x1, float y1, float x2, float y2) {
	   float x = x1 - x2;
	   float y = y1 - y2;
	   return FloatMath.sqrt(x * x + y * y);
	}

}
